package com.ruoyi.controller;

import cn.hutool.core.map.MapUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.dto.FlowTaskDTO;
import com.ruoyi.service.FlowTaskServiceImpl;
import com.ruoyi.service.NextApproverService;
import com.ruoyi.service.SysUserGroupServiceImpl;
import com.ruoyi.vo.DispatchTasksVO;
import com.ruoyi.vo.FlowTaskVO;
import com.ruoyi.vo.NextPotentialApproversVO;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>工作流任务管理<p>
 *
 * @author XuanXuan
 *
 */
@Slf4j
@RestController
@RequestMapping("/flowable/task")
public class FlowTaskController extends BaseController {

    @Autowired
    private FlowTaskServiceImpl flowTaskService;
    @Autowired
    private NextApproverService nextApproverService;

    @Autowired
    private SysUserGroupServiceImpl userGroupService;
    @GetMapping(value = "/myProcess")
    public TableDataInfo myProcess(String name) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        String usersId = userGroupService.getGroupUserStr(userId);

        startPage();
        List<FlowTaskDTO> list = flowTaskService.myProcess(name, usersId);
        return getDataTable(list);
    }

    @PostMapping(value = "/stopProcess")
    public AjaxResult stopProcess(@RequestBody FlowTaskVO flowTaskVo) {
        return flowTaskService.stopProcess(flowTaskVo);
    }

    @PostMapping(value = "/revokeProcess")
    public AjaxResult revokeProcess(@RequestBody FlowTaskVO flowTaskVo) {
        return flowTaskService.revokeProcess(flowTaskVo);
    }

    @GetMapping(value = "/todoList")
    public TableDataInfo todoList(String name,
                                  String deployTime) {

        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        String usersId = userGroupService.getGroupUserStr(userId);

        startPage();
        List<FlowTaskDTO> list = flowTaskService.todoList(name, deployTime, null, usersId);
        return getDataTable(list);
    }

    @GetMapping(value = "/finishedList")
    public TableDataInfo finishedList(@RequestParam Integer pageNum,
                                      @RequestParam Integer pageSize, String name) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        String usersId = userGroupService.getGroupUserStr(userId);

        startPage();
        List<FlowTaskDTO> list = flowTaskService.finishedList(name, usersId);
        return getDataTable(list);
    }

    @GetMapping(value = "/getByBusinessKey")
    public AjaxResult getByBusinessKey(String key) {
        FlowTaskDTO rs = flowTaskService.getByBusinessKey(key);
        return AjaxResult.success(rs);
    }

    @GetMapping(value = "/getByProcInsId")
    public AjaxResult getByProcInsId(String procInsId, String taskId) {
        FlowTaskDTO rs = flowTaskService.getByProcInsId(procInsId, taskId);
        return AjaxResult.success(rs);
    }

    @GetMapping(value = "/flowRecord")
    public AjaxResult flowRecord(String procInsId, String deployId) {
        return AjaxResult.success(flowTaskService.flowRecord(procInsId, deployId));
    }

    @GetMapping(value = "/processVariables/{taskId}")
    public AjaxResult processVariables(@PathVariable(value = "taskId") String taskId, String procInsId) {
        return flowTaskService.processVariables(taskId, procInsId);
    }

    @RequestMapping("/next-approvers")
    public Object getNextApprovers(String processDefinitionType,String taskId,@RequestParam Map params) {
        NextPotentialApproversVO nextPotentialApproversVO = nextApproverService.getNextPotentialApprovers(processDefinitionType,taskId,params);
        Map rs = MapUtil.builder().put("potentialApprovers", nextPotentialApproversVO.getPotentialApprovers())
                .put("nextIsEnd", nextPotentialApproversVO.getNextIsEnd()).build();

        return rs;
    }

    @PostMapping(value = "/complete")
    public AjaxResult complete(@RequestBody FlowTaskVO flowTaskVo) {
        if (flowTaskVo.getFlowableButton() != null) {
            if (flowTaskVo.getFlowableButton().getKey().equals("returnBtn")) {
                flowTaskService.taskReturn(flowTaskVo);
            } else if (flowTaskVo.getFlowableButton().getKey().equals("rejectBtn")) {
                flowTaskService.taskReject(flowTaskVo);
            } else {
                flowTaskService.complete(flowTaskVo);
            }
            return AjaxResult.success();
        }
        return flowTaskService.complete(flowTaskVo);
    }

    @PostMapping(value = "/completeAndUpdateForm")
    public AjaxResult completeAndUpdateForm(String taskId, @RequestBody Map<String, Object> variables) {
        return flowTaskService.completeAndUpdateForm(taskId, variables);
    }

    @PostMapping(value = "/doDispatchTasks")
    public AjaxResult doDispatchTasks(@RequestBody DispatchTasksVO dispatchTasksVo) {
        flowTaskService.doDispatchTasks(dispatchTasksVo);
        return AjaxResult.success();
    }

    @PostMapping(value = "/reject")
    public AjaxResult taskReject(@RequestBody FlowTaskVO flowTaskVo) {
        flowTaskService.taskReject(flowTaskVo);
        return AjaxResult.success();
    }

    @PostMapping(value = "/return")
    public AjaxResult taskReturn(@RequestBody FlowTaskVO flowTaskVo) {
        flowTaskService.taskReturn(flowTaskVo);
        return AjaxResult.success();
    }

    @PostMapping(value = "/returnList")
    public AjaxResult findReturnTaskList(@RequestBody FlowTaskVO flowTaskVo) {
        return flowTaskService.findReturnTaskList(flowTaskVo);
    }

    @DeleteMapping(value = "/delete")
    public AjaxResult delete(@RequestBody FlowTaskVO flowTaskVo) {
        flowTaskService.deleteTask(flowTaskVo);
        return AjaxResult.success();
    }

    @PostMapping(value = "/claim")
    public AjaxResult claim(@RequestBody FlowTaskVO flowTaskVo) {
        flowTaskService.claim(flowTaskVo);
        return AjaxResult.success();
    }

    @PostMapping(value = "/unClaim")
    public AjaxResult unClaim(@RequestBody FlowTaskVO flowTaskVo) {
        flowTaskService.unClaim(flowTaskVo);
        return AjaxResult.success();
    }

    @PostMapping(value = "/delegate")
    public AjaxResult delegate(@RequestBody FlowTaskVO flowTaskVo) {
        flowTaskService.delegateTask(flowTaskVo);
        return AjaxResult.success();
    }

    @PostMapping(value = "/assign")
    public AjaxResult assign(@RequestBody FlowTaskVO flowTaskVo) {
        flowTaskService.assignTask(flowTaskVo);
        return AjaxResult.success();
    }

    @PostMapping(value = "/nextFlowNode")
    public AjaxResult getNextFlowNode(@RequestBody FlowTaskVO flowTaskVo) {
        return flowTaskService.getNextFlowNode(flowTaskVo);
    }


    /**
     * 生成流程图
     *
     * @param processId 任务ID
     */
    @RequestMapping("/diagram/{processId}")
    public void genProcessDiagram(HttpServletResponse response,
                                  @PathVariable("processId") String processId) {
        InputStream inputStream = flowTaskService.diagram(processId);
        OutputStream os = null;
        BufferedImage image = null;
        try {
            image = ImageIO.read(inputStream);
            response.setContentType("image/png");
            os = response.getOutputStream();
            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 生成流程图
     *
     * @param procInsId 流程实例编号
     * @param procInsId 任务执行编号
     */
    @RequestMapping("/flowViewer/{procInsId}/{executionId}")
    public AjaxResult getFlowViewer(@PathVariable("procInsId") String procInsId,
                                    @PathVariable("executionId") String executionId) {
        return AjaxResult.success(flowTaskService.getFlowViewer(procInsId, executionId));
    }
}
